package com.heo.server;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.heo.pub.ApplicationContextUtil;
import com.heo.pub.ServerConfig;

/**
 * Created by zhangcf
 * 使用spring方式，启动服务端程序主入口类
 */
public class MainServer
{
  private static final void shutdownCallback()
  {
    System.out.println("[server]服务器已关闭。");
  }

  public static void main(String[] args)
  {
    InetAddress ia;
    String ip = null;
    try
    {
      ia = InetAddress.getLocalHost();
      ip = ia.getHostAddress();//获得本机的ip地址
    }
    catch (UnknownHostException e1)
    {
      e1.printStackTrace();
    }
    String runEnv = ip + "_" + ServerConfig.PORT;

    System.setProperty("RUN_ENV", runEnv);//设备运行环境变量，方便日志在集群环境下输出

    String path = new MainServer().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();  
    path = new File(path).getParent();
    System.out.println(path);
    System.setProperty("APP_PATH", path);// 因为需要用jar方式启动，而配置文件在jar文件的外面，所以需要这里定义变量，然后在配置文件里引用变量，通过绝对路径来找配置文件。
    PropertyConfigurator.configure(path + "/config/log4j.properties");
    ApplicationContext ctx = new ClassPathXmlApplicationContext("file:" + path + "/config/applicationContext.xml");
    
    ApplicationContextUtil.setApplicationContext(ctx);
    try
    {
      // 注册关闭系统时的退出
      Runtime.getRuntime().addShutdownHook(new Thread()
      {
        @Override
        public void run()
        {
          shutdownCallback();
        }
      });

      // 启动控制台线程
      Thread consoleThread = new Thread(new ConsoleServer());
      consoleThread.start();

      // 启动控制系统线程
      Thread controllerServer = new Thread(new ControllerServer());
      controllerServer.start();

//      NettyServerBootstrap server = ctx.getBean(NettyServerBootstrap.class);
//      server.bind();

      new NettyServerBootstrap().start();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}
